package com.autel.webrtc.demo.aop;


import com.alibaba.fastjson.JSON;
import com.autel.webrtc.demo.common.Result;
import com.autel.webrtc.demo.common.SystemContext;
import com.autel.webrtc.demo.common.storage.ThreadLocalHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

@Slf4j
@Aspect
@Component//将这个类引入spring容器中去
public class HttpRequestAop {


    /**
     * 要处理的方法，包名+类名+方法名
     */
    @Pointcut("execution(public * com.autel.webrtc.demo.controller.rest.*.*(..))")
    public void cut() {
    }

    @Before("cut()")//在调用上面 @Pointcut标注的方法前执行以下方法
    public void doBefore(JoinPoint joinPoint) {//用于获取类方法
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        log.info("url ={}", request.getRequestURI());
        //method
        log.info("method={}", request.getMethod());
        //ip
        log.info("ip={}", request.getRemoteAddr());
        //类方法
        log.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + '.' + joinPoint.getSignature().getName());//获取类名及类方法
        //参数
        List<Object> requestParams = Arrays.asList(joinPoint.getArgs()).stream().filter(arg -> !(arg instanceof HttpServletRequest)).collect(toList());
        log.info("args={}", JSON.toJSONString(requestParams));
        log.info("接收到的上下文参数为{}",SystemContext.getContextMap());
    }

    @After("cut()")//无论Controller中调用方法以何种方式结束，都会执行
    public void doAfter() {
        log.info("------------doAfter---清空线程变量--------");
        SystemContext.clean();
        ThreadLocalHolder.getInstance().clearAll();
    }

    @AfterReturning(returning = "obj", pointcut = "cut()")//在调用上面 @Pointcut标注的方法后执行。用于获取返回值
    public void doAfterReturning(Object obj) {
        if (obj instanceof Result) {
            Result rs=(Result) obj;
                try {
                    if (rs.isSuccess()) {
                        log.info("调用成功");
                    } else {
                        log.info("调用失败:错误信息:{}", JSON.toJSONString(rs.getCode() +":"+rs.getMessage()));
                    }
                } catch (Exception e) {
                    log.info("{}", e);
                }
            }
        }

}
